package cn.wx.fileclient.utils;

/**
 * @author shkstart
 * @create 2020-06-28 11:13
 */

import cn.wx.fileclient.entity.Applicant;
import cn.wx.fileclient.tesseract.OcrChineseRecognizer;
import com.github.jaiimageio.plugins.tiff.TIFFImageWriteParam;

import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Locale;

public class ImageUtil {

    //获取图片中应聘者的信息
    public static Applicant getInfoFromImage(String filePath){
        Applicant applicant = new Applicant();
        try {
            String format = filePath.substring(filePath.indexOf(".")+1);
            String imageContent = new OcrChineseRecognizer().recognizeText(new File(filePath), format);
            applicant.setName(getNameFromImage(imageContent));
            applicant.setEmail(getEmailFromImage(imageContent));
            applicant.setPhone(getPhoneFromImage(imageContent));
            System.out.println(imageContent);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return applicant;
    }

    //从图片读取出来的数据中拿取应聘者的姓名
    public static String getNameFromImage(String content){
        String sub = null;
        String[] datas = null;
        StringBuilder builder = new StringBuilder();
        if (content.indexOf("姓名")>=0){
            sub = content.substring(content.indexOf("姓名")+1);
            datas = sub.split(" ");
            for (int i = 0; datas[i].length()<=3; i++){
                if ((datas[i].trim().length()+builder.length())<=3){
                    builder.append(datas[i].trim());
                }else {
                    break;
                }
            }
        }
        return builder.toString();
    }

    //从图片读取出来的数据中拿取应聘者的邮箱
    public static String getEmailFromImage(String content){
        String email = MatcherAssistUtils.getMatcherStr(content, "\\w+([.-]?\\w+)@\\w+([.-]?\\w+)(.\\w{2,3})+").trim();
        return ("".equals(email)||email==null)? "failure":email;
    }

    //从图片读取出来的数据中拿取应聘者的电话号码
    public static String getPhoneFromImage(String content){
        String phone = MatcherAssistUtils.getMatcherStr(content, "[1]([3-9])[0-9]{9}").trim();
        return ("".equals(phone)||phone==null)? "failure":phone;
    }

    public static File createImage(File imageFile, String imageFormat) {
        File tempFile = null;
        try {
            Iterator readers = ImageIO.getImageReadersByFormatName(imageFormat);
            ImageReader reader = (ImageReader)readers.next();

            ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
            reader.setInput(iis);
            //Read the stream metadata
            IIOMetadata streamMetadata = reader.getStreamMetadata();

            //Set up the writeParam
            TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.CHINESE);
            tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

            //Get tif writer and set output to file
            Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
            ImageWriter writer = (ImageWriter)writers.next();

            BufferedImage bi = reader.read(0);
            IIOImage image = new IIOImage(bi,null,reader.getImageMetadata(0));
            tempFile = tempImageFile(imageFile);
            ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
            writer.setOutput(ios);
            writer.write(streamMetadata, image, tiffWriteParam);
            ios.close();

            writer.dispose();
            reader.dispose();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return tempFile;
    }

    private static File tempImageFile(File imageFile) {
        String path = imageFile.getPath();
        StringBuffer strB = new StringBuffer(path);
        strB.insert(path.lastIndexOf('.'),0);
        return new File(strB.toString().replaceFirst("(?<=//.)(//w+)$", "tif"));
    }


}
